# -*- coding: utf-8 -*-
# @时间：2023/11/7 19:49
# @作者：CJiaの可乐哥
# @文件名：post
# @软件：Pycharm2023
from typing import List

from ninja import Router, Schema, Field, ModelSchema, Query
from django.shortcuts import get_object_or_404
from ninja.pagination import paginate
from system.models import Post

from utils.cj_ninja import MyPagination
from utils.cj_curd import retrieve, delete, update, status

router = Router()


class Filters(Schema):
    id: str = Field(None, alias="post_id")
    name: str = Field(None, alias="name")
    code: str = Field(None, alias="code")
    status: int = Field(None, alias="status")


class PostSchemaIn(ModelSchema):
    class Config:
        model = Post
        model_exclude = ['id', 'create_datetime', 'update_datetime']


class PostSchemaOut(ModelSchema):
    class Config:
        model = Post
        model_fields = "__all__"


@router.delete("/post/{post_id}")
def delete_post(request, post_id: int):
    request.types = "sys:post:delete"
    # 调用删除方法
    result = delete(request, post_id, Post)
    # 返回结果
    return result


@router.put('/post/{post_id}', response=PostSchemaOut)
def update_post(request, post_id: int, data: PostSchemaIn):
    request.types = "sys:post:update"
    # 调用修改方法
    result = update(request, post_id, data, Post)
    # 返回结果
    return result


@router.put("/post/status/{post_id}")
def status_post(request, post_id: int):
    request.types = "sys:post:update"
    # 调用修改状态方法
    result = status(request, post_id, Post)
    # 返回结果
    return result


@router.get("/post/{post_id}", response=PostSchemaOut)
def get_post(request, post_id: int):
    post = get_object_or_404(Post, id=post_id)
    return post


@router.get("/post", response=List[PostSchemaOut])
@paginate(MyPagination)
def list_role(request, filters: Filters = Query(...)):
    qs = retrieve(request, Post, filters)
    return qs
